package parse;

import config.Configuration;
import config.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @CreatedBy richInfo AI
 * @ClassName MapperParse
 * @Date 2021/8/16 2:30 下午
 * @Author xin.yang
 * @Description TODO
 */
public class MapperParse
{

    private Configuration configuration;

    public MapperParse(Configuration configuration)
    {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws Exception
    {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectNodes = rootElement.selectNodes("select");
        for (Element selectNode : selectNodes)
        {
            String id = selectNode.attributeValue("id");
            String parameterType = selectNode.attributeValue("parameterType");
            String resultType = selectNode.attributeValue("resultType");
            String sql = selectNode.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
        List<Element> saveNodes = rootElement.selectNodes("insert");
        for (Element saveNode : saveNodes)
        {
            String id = saveNode.attributeValue("id");
            String parameterType = saveNode.attributeValue("parameterType");
            String resultType = saveNode.attributeValue("resultType");
            String sql = saveNode.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setSql(sql);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }
}
